package cn.sfa.common.taglib;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import javax.wsdl.Output;

import org.jfree.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.sfa.common.utils.CommonUtil;
import cn.sfa.entity.system.FunctionSysCode;
import cn.sfa.entity.system.ModelSysCode;
import cn.sfa.entity.users.SaleUsersLogin;

/**
 * 网页头部
 * @ClassName：MainHeaderTag 
 * @Description：TODO
 * @author：LiXiang
 * @date：2012-7-9 下午3:09:03 
 *
 */
public class MainHeaderTag extends TagSupport {

	private static final long serialVersionUID = 1355396206595036725L;

	Logger logger = LoggerFactory.getLogger(MainHeaderTag.class);

	String menuId;

	@Override
	public int doEndTag() throws JspException {

		return super.doEndTag();
	}

	@Override
	public int doStartTag() throws JspException {

		String path = (String) pageContext.getRequest().getAttribute("path");

		String curURL = (String) pageContext.getRequest().getAttribute(
				"curPath");

		SaleUsersLogin user = (SaleUsersLogin) pageContext.getSession()
				.getAttribute("user");
		List userRole = user.getUserRoles(); // 用户角色
		List<FunctionSysCode> cacheFunction = CommonCache.getInstance()
				.getAllFunction(); // 功能缓存
		List<ModelSysCode> cacheMode = CommonCache.getInstance().getAllModel(); // 模块缓存
		String navURL = "";
		String menuURL = "";
		ModelSysCode currenMoudel = null; // 当前所在模块
		navURL = "/" + curURL.split("/")[1] + "/index"; // 导航匹配
		menuURL = curURL.substring(1, curURL.length()); // 左边菜单匹配
		logger.info("menuURL:" + menuURL + "  | navURL:" + navURL);
		if ("login".equals(curURL.split("/")[2])) {// 登录的时候进行菜单初始化
			navURL = "/news/index";
		}

		// 根据角色取模块
		List<ModelSysCode> userMoudle = new ArrayList<ModelSysCode>();

		for (int j = 0; j < userRole.size(); j++) {
			Map map = (Map) userRole.get(j);
			for (int i = 0; i < cacheMode.size(); i++) {
				ModelSysCode ms = cacheMode.get(i);
				if (ms.getSaleRoleId().equals(map.get("roleId"))) {
					userMoudle.add(ms);
				}
			}
		}

		// 去重复模块
		for (int i = 0; i < userMoudle.size() - 1; i++) {
			for (int j = userMoudle.size() - 1; j > i; j--) {
				if (userMoudle.get(i).getModuleId()
						.equals(userMoudle.get(j).getModuleId())) {
					userMoudle.remove(j);
				}
			}
		}

		StringBuffer buffer = new StringBuffer();

		buffer.append("    <div class=\"top-header\">");
		buffer.append("        <div class=\"userinfo\">");
		buffer.append("            <img src='"
				+ path
				+ "/statics/images/icon-user.gif' style=\"margin-bottom: -6px; margin-right: 4px;\" /><span");
		buffer.append("                id=\"username\">" + user.getUserName()
				+ "(" + user.getLoginName()
				+ ")</span>，您好！<a href=\"" + path
				+ "/login/index/logout\">注销</a>");
		 
		buffer.append("        </div>");
		buffer.append("    </div>");
		buffer.append("    <div class=\"container\">");
		buffer.append("        <!----------- 页面头部 ------------------>");
		buffer.append("        <div class=\"header\">");
		buffer.append("           <h1>");
		buffer.append("               <span>CRM客户关系管理系统</span>");
		buffer.append("            </h1>");
		buffer.append("            <!-----------  网站导航 ------------------>");
		buffer.append("           <ul class=\"navigation\" id=\"navigation\">");

		// 遍历所有模块
		for (int i = 0; i < userMoudle.size(); i++) {

			if (i == 0) {
				buffer.append("<li class=\"navli-l\">");
			} else if (i == userMoudle.size() - 1) {
				buffer.append("<li class=\"bgnone navli-r\">");
			} else {
				buffer.append("<li class=\"navli-m\">");
			}

			if ("1".equals(userMoudle.get(i).getModuleLevel())) {
				if (userMoudle.get(i).getDefaultUrl() != null
						&& userMoudle.get(i).getDefaultUrl().equals(navURL)) {
					currenMoudel = userMoudle.get(i);
					buffer.append("<a href=\"" + path
							+ userMoudle.get(i).getDefaultUrl()
							+ "\" class=\"current\"><span>"
							+ userMoudle.get(i).getModuleName() + "</span></a>");
				} else
					buffer.append("<a href=\"" + path
							+ userMoudle.get(i).getDefaultUrl() + "\" ><span>"
							+ userMoudle.get(i).getModuleName() + "</span></a>");
			}

			buffer.append("</li>");
		}
		buffer.append("            </ul>");
		buffer.append("            <div style=\"clear: both\">");
		buffer.append("            </div>");
		buffer.append("        </div>");

		buffer.append("   <!----------- 页面内容 ------------------>");
		buffer.append("    <div class=\"content\" id=\"content\">");

		// TODO:如果当前是规定不不显示左边菜单
		if(CommonUtil.isEmpty(currenMoudel)){
			//权限拦截
			/*try {
				pageContext.forward(path+"/common/alter.jsp");
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
		}
		else if (!"/news/index".equals(currenMoudel.getDefaultUrl())) {
			buffer.append("<div class='navsite'>"
					+ "<p> 您的位置：<a href='/news/index'>首页</a>&nbsp;&gt;&gt;&nbsp;");
			for (int j = 0; j < cacheFunction.size(); j++) {
				if (cacheFunction.get(j).getFuncUrl().equals(menuURL)) {
					buffer.append("<a href='#'>"
							+ cacheFunction.get(j).getModuleName()
							+ "</a>&nbsp;&gt;&gt;&nbsp;<a href='/"
							+ cacheFunction.get(j).getFuncUrl() + "'>"
							+ cacheFunction.get(j).getFuncName() + "</a>");
				}
			}

			buffer.append("</p>" + "</div>");

			// TODO:左边菜单开始

			buffer.append(" <div class=\"webpart3 submenu\">");
			buffer.append(" 	<div class=\"webpart-head\">");
			buffer.append("   		 <div class=\"webpart-head-item\">");
			buffer.append("    			  <img src='"
					+ path
					+ "/statics/images/add.gif' style=\"margin-right: 4px;\" />");
			if (!CommonUtil.isEmpty(currenMoudel)) {
				buffer.append(currenMoudel.getModuleName());
			}
			buffer.append("   		 </div>");
			buffer.append(" 	</div>");
			buffer.append(" 	<div class=\"webpart-main\">");
			buffer.append(" 		<div class=\"webpart-main-item submenuitem\" style=\"padding-top: 8px;\">");

			// 遍历所有左边模块

			for (int i = 0; i < userMoudle.size(); i++) {
				ModelSysCode msc = userMoudle.get(i);
				if (msc.getParentModuleId().equals(currenMoudel.getModuleId())) {
					buffer.append("<h1>" + msc.getModuleName() + "</h1><ul>");
					for (int j = 0; j < cacheFunction.size(); j++) {
						FunctionSysCode fsc = cacheFunction.get(j);
						if (fsc.getModuleId().equals(msc.getModuleId())) {
							if (fsc.getFuncUrl().equals(menuURL)) {
								buffer.append("<li class='current'><a href='/"
										+ fsc.getFuncUrl() + "'>"
										+ fsc.getFuncName() + "</a></li>");
							} else
								buffer.append("<li><a href='/"
										+ fsc.getFuncUrl() + "'>"
										+ fsc.getFuncName() + "</a></li>");
						}
					}
					buffer.append("</ul>");
				}
			}

			// TODO:左边菜单结束
			buffer.append("			</div>");
			buffer.append("		</div>");
			buffer.append("		<div class=\"webpart-foot\">");
			buffer.append("			<div class=\"webpart-foot-item\">");
			buffer.append("			</div>");
			buffer.append("		</div>");
			buffer.append("</div>");
		}

		Log.info(buffer.toString());

		JspWriter out = pageContext.getOut();
		try {
			out.println(buffer);// 输出到jsp页面
		} catch (IOException e) {

			e.printStackTrace();
		}

		return super.doStartTag();
	}

}
